<?php
/**
 * Assert that checks if all Posts with $id from request $ids group belongs to
 * current user
 *
 * @author Lukas Normantas
 */
class Blog_Assert_AuthorOfEveryPost implements Zend_Acl_Assert_Interface
{
    /**
     * Returns true if every post with $ids in Request param 'group_action'
     * array.
     * This param could be set in Plugin.
     * @see Areal_Controller_Plugin_PostedAction
     *
     * @param  Zend_Acl                    $acl
     * @param  Zend_Acl_Role_Interface     $role
     * @param  Zend_Acl_Resource_Interface $resource
     * @param  string                      $privilege
     * @return boolean
     */
    public function assert(Zend_Acl $acl, Zend_Acl_Role_Interface $role = null,
                           Zend_Acl_Resource_Interface $resource = null,
                           $privilege = null)
    {
        $user_id = Zend_Auth::getInstance()->getIdentity()->getUserId();
        if ($user_id===null) $user_id=0;
        $request = Areal_Controller_Front::getInstance()->getRequest();

        $posted_data = $request->getParam('group_action');
        

        if ( ! isset($posted_data['selected_items']) ) return true;
        $ids = $posted_data['selected_items'];

        // Selects number of selected post whoose do not belong to current user
        $q = Doctrine_Query::create()
            ->select('COUNT(p.id) num_ids')
            ->from('Blog_Post p')
            ->whereIn('p.id', $ids)
            ->andWhere('p.author_id <> ?',$user_id);

        $count_other_users = $q->execute(array(), Doctrine::HYDRATE_SINGLE_SCALAR);

        // if found any posts from selected ones not belonging to this user then fail
        if ($count_other_users != 0) return false;
        return true;
    }
}

